package com.tangruojie.controller;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/servletInputStream")
public class ServletInputStreamController {

    /**
     * 读取 JSON 字符串
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/json")
    public String readJson(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        // 将 inputStream 转为字符串
        String body = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));
        System.out.println("原始请求体内容: " + body);
        return "接收成功: " + body;
    }

    /**
     * 读取二进制数据（比如文件上传）
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/binary")
    public String readBinary(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        byte[] buffer = inputStream.readAllBytes();
        System.out.println("接收到二进制数据长度: " + buffer.length);
        return "二进制数据读取完成，长度: " + buffer.length;
    }


}
